﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "canthread.h"

#include <QLibrary>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->canTypeBox->addItem("USBCAN_E_U");
    ui->canTypeBox->addItem("USBCAN_2E_U");

    ui->baudrateBox->addItem("1000Kbps");
    ui->baudrateBox->addItem("800Kbps");
    ui->baudrateBox->addItem("500Kbps");
    ui->baudrateBox->addItem("250Kbps");
    ui->baudrateBox->addItem("125Kbps");
    ui->baudrateBox->addItem("100Kbps");

    ui->baudrateBox->setCurrentIndex(3);

    CanThread* canThread = CanThread::Instance();

    connect(this, &MainWindow::SignalCanConnect, canThread, &CanThread::SlotCanConnect,
            Qt::BlockingQueuedConnection);
    connect(this, &MainWindow::SignalCanStart, canThread, &CanThread::SlotCanStart);
    connect(this, &MainWindow::SignalCanStop, canThread, &CanThread::SlotCanStop);
    connect(this, &MainWindow::SignalCanRestart, canThread, &CanThread::SlotCanRestart);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::SlotCanRecv(QString& str)
{

}

void MainWindow::SlotCanLog(QString& log)
{

}

void MainWindow::on_connectBtn_clicked()
{
    if(!CanThread::Instance()->isLoad()) return;

    if(!isOpen) {
        qDebug() << "open can";
        emit SignalCanConnect(ui->canTypeBox->currentIndex(), ui->baudrateBox->currentIndex());

        isOpen = CanThread::Instance()->isOpen();
        if(isOpen) {
            ui->connectBtn->setText(u8"断开");
            ui->canTypeBox->setEnabled(false);
            ui->baudrateBox->setEnabled(false);
        }
    }
    else {
        emit SignalCanStop();
        isOpen = false;
        ui->connectBtn->setText(u8"连接");
        ui->canTypeBox->setEnabled(true);
        ui->baudrateBox->setEnabled(true);
    }
}

void MainWindow::on_startBtn_clicked()
{
    if(isOpen) {
        emit SignalCanStart();
    }
}


void MainWindow::on_restartBtn_clicked()
{
    if(isOpen) {
        emit SignalCanRestart();
    }
}

QString MainWindow::getCanTimeStampStr(unsigned long TimeStamp)
{
    QString resultStr = "";

    int hour = TimeStamp/36000000;

    int minute = (TimeStamp - hour*36000000)/600000;

    int second = (TimeStamp - hour*36000000 - minute*600000)/10000;

    int ms = (TimeStamp - hour*36000000 - minute*600000 - second*10000)/10;

    int mms = (TimeStamp - hour*36000000 - minute*600000 - second*10000 - ms*10);

    resultStr = QString("%1:").arg(hour,2,10,QChar('0'));//时

    resultStr += QString("%1:").arg(minute,2,10,QChar('0'));//分

    resultStr += QString("%1:").arg(second,2,10,QChar('0'));//秒

    resultStr += QString("%1:").arg(ms,3,10,QChar('0'));//毫秒

    resultStr += QString::number(mms);//0.1ms

    return resultStr;
}
